package Fragment;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import CalibrationUtils.calibrationutils;
import SQLUtils.sqllite;
import SensorData.SensorData;
import com.example.zelonghu.test_all_without_network.AppContent;
import com.example.zelonghu.test_all_without_network.R;
import Preferences.Preferences;
import Service.BackGroundService;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import static SQLUtils.sqllite.querySD;
import static android.content.Context.SENSOR_SERVICE;

/**
 * @name ControlFragment
 * @class name：ControlFragment
 * @class describe
 * @author zelonghu 
 * @time 2019/4/19 3:38 PM
 * @change
 * @chang time
 * @class describe
 */


public class ControlFragment extends Fragment {
    private Button startSensorButton = null;
    private Button endSensorButton = null;
    private Sensor gyroscopeSensor = null;
    private Sensor proximitySensor = null;
    private TextView showtextview;
    private Button walkflagbutton;
    private Button runflagbutton;
    private Button sleepflagbutton;
    private Button entertainflagbutton;
    private Button eatflagbutton;
    private Spinner indorspinner;
    private Spinner outdorspinner;
    private Queue<SensorData> dataque = null;
    private CheckBox backgroundSensorcheckbox = null;
    SensorEventListener gyroscopeSensorEventListener = null;
    SensorEventListener provimitySensorEventListener = null;
    SQLiteDatabase db = null;
    String dbtablename = null;
    SensorManager sm = null;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //填入fragment_home的布局文件
        View view=inflater.inflate(R.layout.controlfragment_layout,container,false);

        //sqllite.droptable(db,dbtablename);
        sm = (SensorManager)getContext().getSystemService(SENSOR_SERVICE);
        gyroscopeSensor = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        proximitySensor  = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        gyroscopeSensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                Log.i("gyroscope",sensorEvent.values[0] + " "+
                        sensorEvent.values[1] + " " + sensorEvent.values[2]);
                //add new sensordata into the database
                SensorData nsd = new SensorData();
                nsd.setTime(System.currentTimeMillis() + "");
                nsd.setType(AppContent.gyroscopeSensorData);
                nsd.setValue1(sensorEvent.values[0]);
                nsd.setValue2(sensorEvent.values[1]);
                nsd.setValue3(sensorEvent.values[2]);
                //先不写入Flag，等待用户点击停止标定。
                //sqllite.insertSD(db,dbtablename,nsd);
                dataque.add(nsd);
                new showthread(nsd.toString(),showtextview).run();
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {

            }
        };
        provimitySensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                if (sensorEvent.values[0] < proximitySensor.getMaximumRange()) {
                    //there is object
                    Log.i("proximity","something block the phone");

                    //add new sensordata into the database
                    SensorData nsd = new SensorData();
                    nsd.setTime(System.currentTimeMillis() + "");
                    nsd.setType(AppContent.ProximitySensorData);
                    nsd.setValue1(sensorEvent.values[0]);
                    //sqllite.insertSD(db,dbtablename,nsd);
                    dataque.add(nsd);
                    new showthread(nsd.toString(),showtextview).run();
                } else {
                    //nothing happened
                }
            }
            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        };
        Log.i("test","control layout");
        //describe all the button for control
        startSensorButton = (Button)view.findViewById(R.id.startSensorButton);
        startSensorButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // the samplingPeriodUs is about microsecond,means 1000 * 1000 for a second,
                // and the max inteperiod is 0.5s,we should set it properly
                sm.registerListener(gyroscopeSensorEventListener
                        ,gyroscopeSensor,AppContent.RECEIVING_INTERVAL);
                sm.registerListener(provimitySensorEventListener,proximitySensor,
                        AppContent.RECEIVING_INTERVAL);
                new showthread("开始收集",showtextview).run();
            }
        });
        endSensorButton = (Button)view.findViewById(R.id.endSensorButton);
        endSensorButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sm.unregisterListener(gyroscopeSensorEventListener);
                sm.unregisterListener(provimitySensorEventListener);
                //控制显示窗口 control the textview
                if(dataque.size()!=0){
                    new showthread("收集完成",showtextview).run();
                }else{
                    new showthread("没有数据",showtextview).run();
                }
                //insert into sqllite
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_NULL);
                    sqllite.insertSD(db,dbtablename,t);
                }

            }
        });

        //对spinner进行设置 setup spinners
        indorspinner = (Spinner)view.findViewById(R.id.indor_spinner);
        ArrayAdapter<String> indorspinneradapter = new ArrayAdapter<String>(getContext(),
                R.layout.spinner_item_select,
                calibrationutils.getcalibrationkeyarray(0));

        indorspinneradapter.setDropDownViewResource(R.layout.spinner_item_drop);
        indorspinner.setAdapter(indorspinneradapter);
        indorspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String currentstr = adapterView.getItemAtPosition(i).toString();
                int curSymbol = calibrationutils.getcalibrationSymbol(0,currentstr);
                Log.i("currents symbol",curSymbol + "");
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_RUN);
                    sqllite.insertSD(db,dbtablename,t);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        outdorspinner = (Spinner)view.findViewById(R.id.outdor_spinner);
        //为spinner设置Adapter ：setup adapter for the spinner
        ArrayAdapter<String> outdorspinneradapter = new ArrayAdapter<String>(getContext(),
                R.layout.spinner_item_select,
                calibrationutils.getcalibrationkeyarray(1));
        outdorspinneradapter.setDropDownViewResource(R.layout.spinner_item_drop);
        outdorspinner.setAdapter(outdorspinneradapter);
        //设置按钮被选择以后的逻辑 :set up logic motions for the logic of item selceted
        outdorspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String currentstr = adapterView.getItemAtPosition(i).toString();
                int curSymbol = calibrationutils.getcalibrationSymbol(1,currentstr);
                Log.i("currents symbol",curSymbol + "");
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_RUN);
                    sqllite.insertSD(db,dbtablename,t);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        //下面开始设置关于后台检测的checkbox, 读取系统设置，并开启后台进程
        //now follows the description of the background service ,
        // we read its state from the shared perferences and set the checkbox state,and then
        // control the background service
        backgroundSensorcheckbox = (CheckBox)view.findViewById(R.id.backgroundservicebox);
        final Preferences preferences = new Preferences(getContext());
        backgroundSensorcheckbox.setChecked(preferences.checkBackgroundSensoringState());
        Intent intent =new Intent();
        intent.setClass(getContext(), BackGroundService.class);
        if(preferences.checkBackgroundSensoringState()){
            backgroundSensorcheckbox.setChecked(true);
            getActivity().startService(intent);
        }else{
            backgroundSensorcheckbox.setChecked(false);

            getActivity().stopService(intent);
        }
        backgroundSensorcheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent();
                intent.setClass(getContext(), BackGroundService.class);
                Log.i("test","clicked!!");
                if(!backgroundSensorcheckbox.isChecked()){
                    //关闭 close
                    preferences.saveBackgroundSensoringState(false);

                    getActivity().stopService(intent);

                }else{
                    //开启 open
                    preferences.saveBackgroundSensoringState(true);
                    getActivity().startService(intent);
                }
            }
        });

        /*使用了按钮的方式已经被淘汰，5月份删除 :the method of using button is out of date,please delete
        //until May.
        //对按钮进行设置 set up buttons
        runflagbutton = (Button)view.findViewById(R.id.flag_button_run);
        runflagbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_RUN);
                    sqllite.insertSD(db,dbtablename,t);
                }
            }
        });

        walkflagbutton = (Button)view.findViewById(R.id.flag_button_walk);
        walkflagbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_WALK);
                    sqllite.insertSD(db,dbtablename,t);
                }
            }
        });
        entertainflagbutton = (Button)view.findViewById(R.id.flag_button_entertain);
        entertainflagbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_ENTERTAIN);
                    sqllite.insertSD(db,dbtablename,t);
                }
            }
        });
        eatflagbutton = (Button)view.findViewById(R.id.flag_button_eat);
        eatflagbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_EAT);
                    sqllite.insertSD(db,dbtablename,t);
                }
            }
        });
        sleepflagbutton = (Button)view.findViewById(R.id.flag_button_sleep);
        sleepflagbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                while(!dataque.isEmpty()){
                    SensorData t = dataque.poll();
                    t.setFlag(AppContent.STATE_FLAG_SLEEP);
                    sqllite.insertSD(db,dbtablename,t);
                }
            }
        });
        */

        showtextview = (TextView)view.findViewById(R.id.show_text_view);
        return view;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        db= SQLiteDatabase.openOrCreateDatabase(getContext().getFilesDir().getPath()+"/sql.db",null);

        dbtablename = AppContent.tablename;
        dataque = new LinkedList<>();
        calibrationutils.initcalibrationList();//初始化标定数据： init the calibration data
        super.onCreate(savedInstanceState);
    }

    /**
     * @author zelonghu
     * @time 2019/4/13  9:21 PM
     * @describe close and unregisterlistener
     */
    @Override
    public void onDestroy() {
        sm.unregisterListener(gyroscopeSensorEventListener);
        sm.unregisterListener(provimitySensorEventListener);
        db.close();
        super.onDestroy();
    }

    /**
     * @name ControlFragment
     * @class name：ControlFragment
     * @class 用于动态显示内容到textview,使用线程的方式，用法:
     * new showThread(str,textview).run;
     * @author zelonghu
     * @time 2019/4/19 4:12 PM
     * @change
     * @chang time
     * @class describe
     */
    public class showthread extends  Thread{
        String strtoshow;
        TextView textView = null;

        public showthread(String strtoshow, TextView textView) {
            this.strtoshow = strtoshow;
            this.textView = textView;
        }
        @Override
        public void run() {
            textView.setText(strtoshow);
        }
    }

}
